﻿using System;
using System.Configuration;
using System.Linq;
using Wicresoft.fjyc.External.Interface;
using System.DirectoryServices.Protocols;

namespace fjycHRTest
{
    class Program
    {
        private const int MAX_BATCH = 10;
        private static string connstr = ConfigurationSettings.AppSettings.Get("HREntities");


        static void Main(string[] args)
        {
            using (EASLoginProxyClient client = new EASLoginProxyClient())
            {

                //EASLoginProxy client2 = client as EASLoginProxy;
                var context = client.login("user", "kingdee", "eas", "eas", "l2", 1);
                /*
                                using (WSPersonWebServiceFacadeSrvProxyClient person = new WSPersonWebServiceFacadeSrvProxyClient())
                                {
                                    int orgcount = person.getOrgUnitsCount(null, "1980-01-01 00:00:00.0", "2012-08-01 00:00:00.0");
                                    Console.WriteLine("total count : " + orgcount);
                                    int tmp_start = 1;
                                    int tmp_count = MAX_BATCH;

                                    using (fj_hrEntities entity = new fj_hrEntities())
                                    {
                                        while (true)
                                        {
                                            if (tmp_start + tmp_count > orgcount)
                                            {
                                                tmp_count = orgcount - tmp_start + 1;
                                                if (tmp_count < 1) break;
                                            }
                                            string[][] values = null;
                                            try
                                            {
                                                values = person.getOrgUnits(null, "1980-01-01 00:00:00.0", "2012-09-20 00:00:00.0", tmp_start, tmp_count);
                                                int inner_index = 0;
                                                foreach (string[] s in values)
                                                {
                                                    var orgCode = s[0].ToString();
                                                    fj_Org2 org = (from o in entity.fj_Org2
                                                                   where o.OrgCode == orgCode
                                                                   select o).First();
                                                    if (org != null)
                                                    {
                                                        org.OrgCode = s[0];
                                                        org.OrgName = s[1];
                                                        org.OrgName2 = s[2];
                                                        org.UsedFlag = Int32.Parse(s[3]);
                                                        org.ParentOrgCode = s[4];
                                                        org.OrgType = s[5];
                                                        org.OrgProType = s[6];
                                                        org.OrgLevel = s[7];
                                                        org.OrgRegion = s[8];
                                                        org.OrgFileName = s[9];
                                                        org.QueryStartDate = DateTime.Parse("1980-01-01 00:00:00.0");
                                                        org.QueryEndDate = DateTime.Parse("2012-08-01 00:00:00.0");
                                                    }

                                                    else
                                                    {
                                                        org = new fj_Org2();
                                                        org.OrgCode = s[0];
                                                        org.OrgName = s[1];
                                                        org.OrgName2 = s[2];
                                                        org.UsedFlag = Int32.Parse(s[3]);
                                                        org.ParentOrgCode = s[4];
                                                        org.OrgType = s[5];
                                                        org.OrgProType = s[6];
                                                        org.OrgLevel = s[7];
                                                        org.OrgRegion = s[8];
                                                        org.OrgFileName = s[9];
                                                        org.QueryStartDate = DateTime.Parse("1980-01-01 00:00:00.0");
                                                        org.QueryEndDate = DateTime.Parse("2012-08-01 00:00:00.0");
                                                        org.index = tmp_start + tmp_count;

                                                        entity.AddTofj_Org2(org);
                                                        inner_index++;
                                                    }

                                                    try
                                                    {
                                                        entity.SaveChanges();
                                                        Console.WriteLine(s[1] + " has been insert into database.index : " + (tmp_start + inner_index));
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Console.WriteLine(ex.Message);

                                                    }
                                   
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine(ex.Message);
                                                Console.WriteLine("start:" + tmp_start + ";count:" + tmp_count);

                                            }
                                            tmp_start += tmp_count;
                                        }
                                    }
                                }
                                */

                using (WSPersonWebServiceFacadeSrvProxyClient person = new WSPersonWebServiceFacadeSrvProxyClient())
                {
                    int count = person.getPersonsCount("1980-01-01 00:00:00.0", "2012-08-01 00:00:00.0");
                    Console.WriteLine("total count : " + count);
                    int tmp_start = 1;
                    int tmp_count = MAX_BATCH;

                    using (HREntities entity = new HREntities())
                    {
                        while (true)
                        {
                            if (tmp_start + tmp_count > count)
                            {
                                tmp_count = count - tmp_start + 1;
                                if (tmp_count < 1) break;
                            }
                            string[][] values = null;
                            try
                            {
                                values = person.getPersons("1980-01-01 00:00:00.0", "2012-08-01 00:00:00.0", tmp_start, tmp_count);
                                int inner_index = 0;
                                foreach (string[] s in values)
                                {
                                    var personCode = s[2].ToString();
                                    FJ_HR2 record = (from r in entity.FJ_HR2
                                                     where r.PERSONCODE == personCode
                                                     select r).First();

                                    if (record != null)
                                    {
                                        string[] uidAndMail = GetLDAPUidAndMail(s[1], s[8], s[9]);
                                        record.PERSONID = s[0];
                                        record.CNAME = s[1];
                                        record.PERSONCODE = s[2];
                                        record.GENDER = Int32.Parse(s[3]);
                                        if (s[4] == null)
                                            record.BIRTH = null;
                                        else
                                            record.BIRTH = DateTime.Parse(s[4]);
                                        record.EMAIL = s[5];
                                        record.COMPANY = s[6];
                                        record.COMPANYCODE = s[7];
                                        record.DEPT = s[8];
                                        record.DEPTCODE = s[9];
                                        record.MANAGEWORK = s[10];
                                        record.SEQUENCEINDEPT = s[11];
                                        record.POSITIONTYPENAME = s[12];
                                        record.POSITIONTYPECODE = s[13];
                                        record.POSITIONNAME = s[14];
                                        record.POSITIONCODE = s[15];
                                        record.POLITICALFACENAME = s[16];
                                        record.POLITICALFACECODE = s[17];
                                        record.EMPLOYEEPROPNAME = s[18];
                                        record.EMPLOYEEPROPCODE = s[19];
                                        if (s[20] == null)
                                            record.JOBSTART = null;
                                        else
                                            record.JOBSTART = DateTime.Parse(s[20]);
                                        record.STATUS = s[21];
                                        record.STATUSCODE = s[22];
                                        record.DIPLOMANAME = s[23];
                                        record.DIPLOMACODE = s[24];
                                        record.DELETESTATUS = Int32.Parse(s[25]);
                                        record.UNKNOW1 = s[26];
                                        record.QUERYSTARTDATE = DateTime.Parse("2012-01-01");
                                        record.QUERYENDDATE = DateTime.Parse("2012-07-01");
                                    }
                                    else
                                    {
                                        record = new FJ_HR2();

                                        //fj_HR2 record = new fj_HR2();
                                        record.PERSONID = s[0];
                                        record.CNAME = s[1];
                                        record.PERSONCODE = s[2];
                                        record.GENDER = Int32.Parse(s[3]);
                                        if (s[4] == null)
                                            record.BIRTH = null;
                                        else
                                            record.BIRTH = DateTime.Parse(s[4]);
                                        record.EMAIL = s[5];
                                        record.COMPANY = s[6];
                                        record.COMPANYCODE = s[7];
                                        record.DEPT = s[8];
                                        record.DEPTCODE = s[9];
                                        record.MANAGEWORK = s[10];
                                        record.SEQUENCEINDEPT = s[11];
                                        record.POSITIONTYPENAME = s[12];
                                        record.POSITIONTYPECODE = s[13];
                                        record.POSITIONNAME = s[14];
                                        record.POSITIONCODE = s[15];
                                        record.POLITICALFACENAME = s[16];
                                        record.POLITICALFACECODE = s[17];
                                        record.EMPLOYEEPROPNAME = s[18];
                                        record.EMPLOYEEPROPCODE = s[19];
                                        if (s[20] == null)
                                            record.JOBSTART = null;
                                        else
                                            record.JOBSTART = DateTime.Parse(s[20]);
                                        record.STATUS = s[21];
                                        record.STATUSCODE = s[22];
                                        record.DIPLOMANAME = s[23];
                                        record.DIPLOMACODE = s[24];
                                        record.DELETESTATUS = Int32.Parse(s[25]);
                                        record.UNKNOW1 = s[26];
                                        record.QUERYSTARTDATE = DateTime.Parse("2012-01-01");
                                        record.QUERYENDDATE = DateTime.Parse("2012-07-01");

                                        entity.AddToFJ_HR2(record);

                                        record.O_INDEX = tmp_start + inner_index;

                                        inner_index++;
                                    }
                                    try
                                    {
                                        entity.SaveChanges();
                                        Console.WriteLine(s[1] + " has been insert into database.index : " + (tmp_start + inner_index));
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);

                                    }

                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                Console.WriteLine("start:" + tmp_start + ";count:" + tmp_count);

                            }
                            tmp_start += tmp_count;
                        }
                    }

                }
                Console.Read();
            }
        }

        public static string GetLDAPConditions(string deptCode)
        {
            using (HREntities entity = new HREntities())
            {
                FJ_ORG2 org = (from o in entity.FJ_ORG2
                               where o.ORGCODE == deptCode
                               select o).First();
                string condition = string.Empty;
                if (org != null)
                {
                    var parentOrgCode = org.PARENTORGCODE;
                    while (true)
                    {
                        var result = (from o in entity.FJ_ORG2
                                      where o.ORGCODE == parentOrgCode
                                      select o);

                        if (result.Count() > 0)
                        {
                            FJ_ORG2 orgs = result.First();
                            condition = condition + ",OU=" + orgs.ORGNAME;
                            parentOrgCode = orgs.PARENTORGCODE;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                return condition;
            }
        }

        public static string[] GetLDAPUidAndMail(string cName, string deptName, string deptCode)
        {
            using (LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier("10.188.239.105"), null, AuthType.Anonymous))
            {
                ldap.SessionOptions.ProtocolVersion = 3;

                //var di = ldap.Directory;
                string condition = GetLDAPConditions(deptCode);
                string targetOu = string.Format("CN={0},OU={1}{2},O=福建烟草", cName, deptName, condition);

                // create a search filter to find all objects
                string ldapSearchFilter = "(objectClass=*)";
                string[] attribs = { "mail", "uid" };
                string[] result = new string[2];
                try
                {
                    SearchRequest searchRequest = new SearchRequest
                                                    (targetOu,
                                                      ldapSearchFilter,
                                                      SearchScope.Subtree,
                                                      attribs);

                    // cast the returned directory response as a SearchResponse object
                    SearchResponse searchResponse =
                                (SearchResponse)ldap.SendRequest(searchRequest);

                    // enumerate the entries in the search response
                    foreach (SearchResultEntry entry in searchResponse.Entries)
                    {
                        SearchResultAttributeCollection attributes = entry.Attributes;

                        foreach (DirectoryAttribute attribute in attributes.Values)
                        {
                            for (int i = 0; i < attribute.Count; i++)
                            {
                                if (attribute[i] is string)
                                {
                                    if (attribute.Name == "mail")
                                    {
                                        result[0] = attribute[i].ToString();
                                    }
                                    else if (attribute.Name == "uid")
                                    {
                                        result[1] = attribute[i].ToString();
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex) { }
                return result;
            }
        }



    }
}
